import router from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist
let isFal = false
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {

      next({
        path: '/'
      })
      NProgress.done()
    } else {
      // sessionStorage.removeItem('qx')
      // if (sessionStorage.getItem('qx')) {
       
      //   window.location.href = process.env.VUE_APP_BASE_API + "/#/index"

      // } else {
      //   next()
      // }
       // 根据roles权限生成可访问的路由表
      const accessRoutes = await store.dispatch('permission/generateRoutes');
     
      router.addRoutes(accessRoutes)
      next()

    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {

      next()
    } else {

      // next(`/login?redirect=${to.path}`)
      window.location.href = process.env.VUE_APP_BASE_API + "/#/login"

      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
